package com.helloags;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.esri.arcgis.interop.AutomationException;
import com.esri.arcgis.server.IServerLog;
import com.esri.arcgis.server.IServerLogQuery;
import com.esri.arcgis.server.IServerObjectAdmin2;
import com.esri.arcgis.server.IServerObjectAdmin2Proxy;
import com.esri.arcgis.server.ServerConnection;
import com.esri.arcgis.system.ServerInitializer;

public class GetServerLog2 {

	public static void main(String[] args) throws AutomationException,
			IOException, DocumentException {
		ServerInitializer si = new ServerInitializer();
//		si.initializeServer("*", "zhushijie", "zsj123456");
		si.initializeServer("*", "arcgismanager", "123456");

			ServerConnection conn = new ServerConnection();
			conn.connect("192.168.3.106", "*", "zhushijie", "zsj123456");
//			conn.connect("192.168.3.107", "*", "arcgismanager", "123456");

			IServerObjectAdmin2 soa = new IServerObjectAdmin2Proxy(conn.getServerObjectAdmin());
			IServerLog log = soa.getServerLog();
			IServerLogQuery logQuery = log.createQuery();
//			logQuery.setStartIndex(10);
//			logQuery.setStartIndex(500000);
			logQuery.setMaxRecords(100000);
			logQuery.setLevel(2);
			
//			IServerStatistics serverStatistics = new IServerStatisticsProxy(soa);
//			IStatisticsResults statisticsResults = serverStatistics.getAllStatisticsForTimeInterval(esriServerStatEvent.esriSSEContextReleased, esriServerTimePeriod.esriSTPNone, 0, 1, "", "", "");
//			IStatisticsResults statisticsResults = serverStatistics.getAllStatisticsForTimeInterval(esriServerStatEvent.esriSSEServerObjectCreated, esriServerTimePeriod.esriSTPNone, 0, 1, "search", "GlobeServer", "");
//			IServerTimeRange timeRange = new IServerTimeRangeProxy(statisticsResults);
//			Date startTime = timeRange.getStartTime();
//			Date startTime = 
			java.sql.Date startTime = java.sql.Date.valueOf("2012-09-14");
			Date endTime = new Date(System.currentTimeMillis());
//			java.sql.Date endTime = java.sql.Date.valueOf("2012-09-14");
//			
			logQuery.setStartTime(startTime);
			logQuery.setEndTime(endTime);

			String logRecords = log.getLogRecords(logQuery);
			Document doc = DocumentHelper.parseText(logRecords);
			Element root = doc.getRootElement();
			Iterator iter = root.elementIterator();
			while(iter.hasNext()){
				Element ele = (Element)iter.next();
				System.out.print("time: " + ele.attributeValue("time"));
				System.out.print("\tlevle:" + ele.attributeValue("type"));
				System.out.println("\tMessage:" + ele.getText());
			}
			System.out.println(logRecords);
			conn.release();
	}

}
